package com.example.lenovo.testdemo;

import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.lenovo.testdemo.adapter.MainAdapter;
import com.example.lenovo.testdemo.bean.ResBean;
import com.example.lenovo.testdemo.utils.CharUtil;
import com.example.lenovo.testdemo.utils.DialogUtil;
import com.example.lenovo.testdemo.utils.FileUtil;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    ArrayList<ImageBean> imgs = null;//手机中所有的图片列表
    ArrayList<String> results = null;//上传失败列表
    int loadSuccess = 0, loadFailure = 0;
    int selectCount = 0;
    private RecyclerView items;
    private TextView tvNum, tvProgress, tvResult;
    private ProgressBar pbProgress;
    private Button btnLoad;
    private int completeNum = 0;
    private OkHttpClient mOkHttpClient;
    private MaterialDialog dialog;


    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static final String urlPath = "http://112.74.38.81:8080/oa/Image/upload";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tvNum.setText("已经选择图片数目:" + selectCount);
                    break;
                case 1:
                    for (ImageBean bean : imgs) {
                        if (bean.isIcSelect()) {
                            if (CharUtil.chinsesExistence(bean.getFileName())) {
                                Toast.makeText(MainActivity.this, bean.getName() + ",路径存在中文，无法上传", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (FileUtil.getFilesize(bean.getFileName()) > 1024 * 1024) {
                                Toast.makeText(MainActivity.this, bean.getName() + ",文件大小大于1M，无法上传", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }

                    }
                    mHandler.sendEmptyMessage(2);
                    break;
                case 2:
                    uploadPic();
                    break;
                case 3:
                    //更新dialog界面
                    if (dialog != null && dialog.isShowing()) {
                        int loadreslut = loadFailure + loadSuccess;
                        tvProgress.setText("上传进度" + loadreslut + "/" + selectCount);
                        pbProgress.setProgress(loadreslut);
                        //下载完毕
                        if (loadreslut == selectCount) {
                            tvResult.setText("成功：" + loadSuccess + ",失败：" + loadFailure);
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();
    }

    private void initView() {
        items = findViewById(R.id.rlv_items);
        tvNum = findViewById(R.id.tv_num);
        btnLoad = findViewById(R.id.btn_load);

        MainAdapter adapter = new MainAdapter(this, imgs);
        items.setAdapter(adapter);
        //图片被选择的监听
        adapter.setOnItemSelectListener(new MainAdapter.OnItemSelectListener() {
            @Override
            public void onItemSelect(ImageBean bean, boolean isCheck) {
                if (isCheck) {
                    selectCount++;
                } else {
                    selectCount--;
                }
                mHandler.sendEmptyMessage(0);
            }
        });
        items.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));


        btnLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //准备上传的业务
                mHandler.sendEmptyMessage(1);
            }
        });


    }

    private void initData() {
        imgs = new ArrayList<>();
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, null, null, null);
        while (cursor.moveToNext()) {
            //获取图片的名称
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
//            Log.d("zouzhihao ", "name: " + name);
            //获取图片的路径
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//            Log.d("zouzhihao ", "data: " + new String(data));
            //获取图片的详细信息
            String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
//            Log.d("zouzhihao ", "desc: " + desc);

            ImageBean bean = new ImageBean();

            bean.setDesc(desc);
            bean.setName(name);
            bean.setFileName(new String(data, 0, data.length - 1));
            imgs.add(bean);
        }
    }

    //
    private void uploadPic() {
        loadFailure = 0;
        loadSuccess = 0;
        //dialog界面
        dialog = DialogUtil.showDialog(MainActivity.this);
        tvProgress = (TextView) dialog.findViewById(R.id.tv_progress);
        pbProgress = (ProgressBar) dialog.findViewById(R.id.pb_progress);
        tvResult = (TextView) dialog.findViewById(R.id.tv_result);
        pbProgress.setMax(selectCount);
        tvProgress.setText("上传进度" + completeNum + "/" + selectCount);

        results = new ArrayList<>();

        for (final ImageBean bean : imgs) {
            if (bean.isIcSelect()) {
                sendMultipart(bean);
            }

        }

    }

    private void sendMultipart(ImageBean bean){
        mOkHttpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fromname", "upload")
                .addFormDataPart("followchatid", "22")
                .addFormDataPart("nodeid", "127.0.0.1")
                .addFormDataPart("nodeidport", "8000")
                .addFormDataPart("files", bean.getName(),
                        RequestBody.create(MEDIA_TYPE_PNG, new File(bean.getFileName())))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")
                .url(urlPath)
                .post(requestBody)
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("zouzhihao" , e.getMessage());
                loadFailure++;
                mHandler.sendEmptyMessage(3);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.d("zouzhihao" , "Json:" + result);
                ResBean bean = new Gson().fromJson(result , ResBean.class);
                if(TextUtils.isEmpty(bean.getErr())){
                    loadSuccess++;
                    mHandler.sendEmptyMessage(3);
                }else {
                    loadFailure++;
                    mHandler.sendEmptyMessage(3);
                }
            }
        });
    }


}
